//
//  HMComposeToolBar.swift
//  MyWeibo
//
//  Created by apple on 16/4/26.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit

//使用枚举区分不同类型的点击
enum HMComposeToolBarButtonType: Int {
    
    case Picture = 0,Mention,Trend,Emoticon,Add
}



class HMComposeToolBar: UIStackView {
    
    
    var isSystemKeyboard: Bool = true {
        didSet{
            
            let button = self.viewWithTag((HMComposeToolBarButtonType.Emoticon).rawValue) as? UIButton
            
            var name = "compose_keyboardbutton_background"
            // 调整表情按钮的图标
            if isSystemKeyboard {
                // 显示笑脸图标
                name = "compose_emoticonbutton_background"
            }
            button?.setImage(UIImage(named: "\(name)_highlighted"), forState: UIControlState.Highlighted)
            button?.setImage(UIImage(named: name), forState: UIControlState.Normal)
        }
    }
    
    //按钮点击要执行的闭包
    
    var buttonClickClosure:((type:HMComposeToolBarButtonType)->())?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
        
        //设置子控件相等并且填充父控件
        distribution = .FillEqually
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI(){
        
        //调用方法加载控件
        addChildButton("compose_toolbar_picture", type: .Picture)
        addChildButton("compose_mentionbutton_background", type: .Mention)
        addChildButton("compose_trendbutton_background", type: .Trend)
        addChildButton("compose_emoticonbutton_background", type: .Emoticon)
        addChildButton("compose_add_background", type: .Add)
        
    }
    
    
    //创建方法 通过名字 和 控件类型 加载控件  两个参数 控件名字 控件类型
    private func addChildButton(imageNamed:String,type:HMComposeToolBarButtonType){
        
        //创建button
        let button = UIButton()
        //添加按钮点击事件
        button.addTarget(self, action: "childButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
        //取到枚举的原始值
        button.tag = type.rawValue
        
        //设置不同状态下的按钮图片
        button.setImage(UIImage(named:imageNamed), forState: UIControlState.Normal)
        button.setImage(UIImage(named:"\(imageNamed)_highlighted"), forState: UIControlState.Highlighted)
        
        //设置不同状态下的背景图片
        button.setBackgroundImage(UIImage(named: "compose_toolbar_background"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "compose_toolbar_background"), forState: UIControlState.Highlighted)
        
        addArrangedSubview(button)
    }
    
    //按钮点击方法的实现
    @objc private func childButtonClick(button:UIButton){
        
        //调用闭包
        buttonClickClosure?(type:HMComposeToolBarButtonType(rawValue: button.tag)!)
    }
}
